<?php
/**
 * 生成缩略图并上传
 */
ini_set('memory_limit', '256M');

include_once '../lib/config.php';
include_once '../lib/Db.class.php';
include_once '../lib/Model.class.php';
include_once '../lib/Upyun.class.php';
include_once '../lib/function.php';

$redis = new Redis();
$redis->connect(REDIS_IP, "6379"); //php客户端设置的ip及端口
if (!$redis) {
    die('redis connect fail');
}

$redis->auth(REDIS_PASS);
$redis->select(5);

$GLOBALS['config']['master']['db_database'] = 'dc211';
$GLOBALS['config']['slave']['db_database']  = 'dc211';

$model = new Db;
$upyun = new UpYun(UPYUN_BUCKET_ESM, UPYUN_USER, UPYUN_PASS);

// Set a maximum height and width
$width = 350;
$height = 220;

// 查看总进程数
$result = shell_exec("ps aux|grep queue_capture|grep -v grep|wc -l");
$result = intval(trim($result));
if($result >= 5) {
    echo "[".date('Y-m-d H:i:s')."] over process $result \n";
    exit;
}

$limit = 20;
while ($limit--) {
    $stop = $redis->get('LNPAN_QUEUE_STOP');
    if($stop) {
        var_dump('stop');
        break;
    }

    $default_data = $redis->lPop('dc211:slist');
    if(!$default_data) {
        var_dump('finished.');
        break;
    }

    $data = json_decode($default_data, true);
    $url  = rtrim(trim($data['slink']), '/');
    $filename = './thumbs/' . md5($url) . '.jpg';

    if(!file_exists($filename) || filesize($filename) < 5000) {
        $header = getOnlyHeader($url);
        if($header['errno'] > 0) {
            echo $header['errmsg'] ."\n";
            $redis->lPush('dc211:host_invalid', $data['id'] . ":" . $url . ':' . json_encode($header));
            $ret = $model->query('update slist set hasThumb=7 where id='.$data['id']);
            continue;
        }

        $shell = "LC_CTYPE=en_US.UTF-8 /usr/local/bin/casperjs capture.js '{$url}' '{$filename}'";
        echo "[".date('Y-m-d H:i:s')."] $shell\n";
        $result = shell_exec($shell);
        echo "$result\n";
    }

    if(file_exists($filename) && filesize($filename) > 5000) {
    	echo2($filename.':'.filesize($filename));

	    // Get new dimensions
        list($width_orig, $height_orig) = getimagesize($filename);

        $max_height = intval($width_orig * $height / $width);
        if($max_height > $height_orig) {
            $max_height = $height_orig;
        }

        // Resample
        $image_p = imagecreatetruecolor($width, $height);
        $image = imagecreatefromjpeg($filename);
        imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $max_height);

        // Output
        imagejpeg($image_p, $filename, 100);
    	imagedestroy($image_p);
    	imagedestroy($image);
    	unset($image, $image_p);

        try {
            $fh = fopen($filename, 'rb');
            $upyun->writeFile('/' . md5($url) . '.jpg', $fh, True); //上传图片，自动创建目录
            fclose($fh);

            $ret = $model->query('update slist set hasThumb=1 where id='.$data['id']);
            if(!$ret) {
                var_dump($model->error());
                $redis->lPush('dc211:update_failed', $model->error());
                $redis->rPush("dc211:slist", $default_data);
                $model->close();
            }
	        
            echo2('upload success, '.$data['id'] . ':http://dl.sm48.com/' . md5($url) . '.jpg'); 
            $redis->lPush('dc211:upload_success', $data['id'] . ':http://dl.sm48.com/' . md5($url) . '.jpg');
        }
        catch(Exception $e) {
            $error = $data['id'].':'.$e->getCode().':'.$e->getMessage();
            echo2($error);

            $redis->lPush('dc211:upload_failed', $error);
            $redis->rPush("dc211:slist", $default_data);
        } 
    } else {
        echo "$filename cant find:" . $url . ":" . @filesize($filename) ."\n";
        $redis->lPush('dc211:down_error', $data['id'] . ':' . "$filename cant find:" . $url . ":" . @filesize($filename));

        $ret = $model->query('update slist set hasThumb=5 where id='.$data['id']);

        //@unlink($filename);
    }

    //die('die');
}

echo2('loop:'.$limit);
sleep(5);
